package com.quick.develop.flowable.listener;

import com.quick.develop.framework.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;

import static com.quick.develop.framework.utils.number.NumericUtil.div;
import static com.quick.develop.framework.utils.number.NumericUtil.getBigDecimal;

/**
 * @author junyuan.liu
 * @description:  多实例完成条件 权重比例 count只能是 0-1的值
 * @date 2022/5/25 18:31
 */
@Component("multiInstance")
@Slf4j
public class MultiInstanceCompleteTask implements Serializable {
    private static final long serialVersionUID = -237284739157277034L;

    public boolean completionCondition(DelegateExecution execution, String count) {
        boolean flag = true;
        try {
            //总的任务数量
            Integer nrOfInstances = (Integer) execution.getVariable("nrOfInstances");
            //当前获取的任务数量
            Integer nrOfActiveInstances = (Integer) execution.getVariable("nrOfActiveInstances");
            //已经完成的会签任务数量
            Integer nrOfCompletedInstances = (Integer) execution.getVariable("nrOfCompletedInstances");
            log.info("总的任务：{}，当前活动任务：{}，已完成任务：{}",
                    nrOfInstances ,nrOfActiveInstances ,nrOfCompletedInstances);
            log.info("完成权重：{}", count);
            if (StringUtils.isBlank(count)) {
                return nrOfInstances.equals(nrOfCompletedInstances);
            }else {
                BigDecimal bc = getBigDecimal(count, BigDecimal.ZERO);
                if (Objects.nonNull(bc)) {
                    if (bc.equals(BigDecimal.ZERO)) {
                        flag = nrOfInstances.equals(nrOfCompletedInstances);
                    }else {
                        BigDecimal div = div(new BigDecimal(nrOfCompletedInstances), new BigDecimal(nrOfInstances), 1);
                        flag = div.compareTo(bc) >= 0;
                    }
                }else {
                    return nrOfInstances.equals(nrOfCompletedInstances);
                }
            }
        }catch (Exception e){
            log.error("权重计算错误：{}", e.getMessage());
            flag = false;
            e.printStackTrace();
        }
        log.info("是否已经完成：{}", flag);

        return flag;
    }
}
